package com.hhxy.service;

import com.hhxy.mapper.UserMapper;
import com.hhxy.pojo.User;
import com.hhxy.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost方法被调用了");
        this.doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet方法被调用了");
        //Tomcat会将来自浏览器的数据使用IS遍历，需要进行转码防止乱码
        request.setCharacterEncoding("utf-8");
        //1、接收请求数据，接收用户注册的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //2、使用MyBatis完成查询
        //2.1 获取SqlSessionFactory对象
        SqlSessionFactory sqlSF = SqlSessionFactoryUtils.sqlSF();
        //2.2 获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //2.3 获取Mapper接口对象
        UserMapper userMapper = sqlS.getMapper(UserMapper.class);
        /*----------------------核心代码（其他的可以CV）----------------------------*/
        //2.4 执行SQL语句
        User user1 = userMapper.selectByUsername(username);

        //3、处理结果，发送响应数据
        //3.1 设置响应数据格式
//        response.setContentType("text/html;charset=utf-8");
        response.setHeader("content-type","text/html;charset=utf-8");
        //3.2 获取响应数据输出流，用于响应数据
        PrintWriter pw = response.getWriter();
        pw.write("你是煮");
        //3.3 判断是否注册成功
        if (user1 != null) {
            pw.write("该用户名已存在，注册失败！");
        }else{
            userMapper.add(user);
            sqlS.commit();
            pw.write("注册成功！<br/>");
            pw.write("你注册的用户名："+username+"<br/>");
            pw.write("你注册的密码："+password);
        }
        /*-------------------------------------------------------------------------*/
        //4、 释放资源
        sqlS.close();
    }
}
